<template>
  <div class="container">
    <van-list>
      <van-cell v-for="item in list" :key="item" :title="item.address" @dblclick="setNow(item)" />
    </van-list>
    <div>
      <van-field v-model="tranIcon.address" label="账号" placeholder="请输入地址" />
      <van-field v-model="tranIcon.balance" label="money" placeholder="请输入money" type="number" />
      <button @click="giveMoney">转账</button>
      <div>当前地址：{{ nowInfo.address }}</div>
      <div>当前钱包余额{{ nowInfo.balance }}MTH</div>
    </div>
  </div>
</template>

<script setup>
import {
  ethers,
  JsonRpcProvider,
  formatEther,
  formatUnits,
  parseEther,
  getBigInt,
  Interface
} from 'ethers';
import { reactive, ref } from 'vue';

// 合约的 ABI
const tokenAbi = [
  // 省略其他方法，只保留示例用到的函数
  'function name() external view returns (string)',
  'function symbol() external view returns (string)',
  'function decimals() external view returns (uint8)',
  'function owner() external view returns (address)',
  'function totalSupply() external view returns (uint256)',
  'function balanceOf(address account) external view returns (uint256)',
  'function transfer(address recipient, uint256 amount) public returns (bool)',
  'event Transfer(address indexed from, address indexed to, uint256 value)'
];

// 合约地址
const tokenAddress = '0xe7f1725E7734CE288F8367e1Bb143E90bb3F0512';
let providerInit = null;

const tranIcon = reactive({
  address: '',
  balance: ''
});
const nowInfo = reactive({
  address: '',
  balance: '',
  provider: null,
  contract: null
});
// 连接到以太坊网络（使用 MetaMask 的 provider）
const list = ref([]);
async function main() {
  providerInit = new JsonRpcProvider(import.meta.env.VITE_INFURA_LOCAL);
  list.value = await providerInit.listAccounts();
  // console.log(" list", list.value);
  setNow(list.value[0]);
}

async function setNow(apProvider) {
  const { address, provider } = apProvider;
  const block = await providerInit.getBlockNumber();

  nowInfo.address = address;
  const signer = await providerInit.getSigner(address);
  nowInfo.contract = new ethers.Contract(tokenAddress, tokenAbi, signer);
  // 不可以用代理对象
  let app = new ethers.Contract(tokenAddress, tokenAbi, signer);
  // console.log('block', nowInfo.contract);
  console.log('block', app.interface);
  const interfaceApp = app.interface;
  // console.log('block2', new Interface(tokenAbi));
  nowInfo.balance = formatEther(String(await nowInfo.contract.balanceOf(nowInfo.address)));
  app.on('Transfer', (from, to, value) => {
    // console.log("Transfer Event:", from, to,);
    console.log('Transfer Event:', value);
    // console.log("Transfer Event:", getBigInt(value) + 1n);
    // console.log("Transfer Event:", formatUnits(value, "ether"));
    // console.log("Transfer Event:", formatUnits(value, "gwei"));
    // console.log("Transfer Event:", parseEther(formatUnits(value, "gwei"), 18));
  });

  const transferEvents = await app.queryFilter('Transfer');

  console.log('transferEvents', transferEvents);

  // 合约的另外一种调用方式
  // const runContract = nowInfo.contract.connect();
  // const tx = await runContract.transfer(
  //   "0x70997970C51812dc3A010C7d01b50e0d17dc79C8",
  //   parseEther(1000)
  // );
  // await tx.wait();
  // console.log("runContract", runContract, nowInfo.contract);

  nowInfo.provider = provider;
  // 了解合约的数据结构 根据合约的地址可以获取合约的所有数据
  const contractInfo = await providerInit.getStorageAt(tokenAddress, 1);
  console.log(contractInfo);
}

async function giveMoney() {
  if (await nowInfo.contract.transfer.staticCall(tranIcon.address, parseEther(tranIcon.balance))) {
    const tx = await nowInfo.contract.transfer(
      tranIcon.address,
      parseEther(tranIcon.balance)
      // 此处有疑问
      // {
      //   gasPrice: parseEther("1", "gwei"), // 合理的 gasPrice
      //   gasLimit: 31000, // 合理的 gasLimit
      // }
    );

    console.log('Transfer Transaction:', tx);
  }
}

main();
</script>

<style scoped>
.container {
  display: flex;
}
</style>
